#!/bin/bash

# 启动所有服务脚本
# 包括：TCP服务器 + 心跳处理器 + WebSocket服务器

set -e

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_ROOT="$( cd "$SCRIPT_DIR/../../" && pwd )"

echo "========================================"
echo "启动所有服务"
echo "========================================"
echo ""

# 检查PHP是否安装
if ! command -v php &> /dev/null; then
    echo "❌ PHP未安装，请先安装PHP"
    exit 1
fi

# 检查Redis是否运行
if ! redis-cli ping &> /dev/null; then
    echo "❌ Redis未运行，请先启动Redis"
    exit 1
fi

# 检查MySQL是否运行
if ! mysql -u root -p"" -e "SELECT 1" &> /dev/null 2>&1; then
    echo "⚠️  MySQL连接可能有问题，请检查配置"
fi

# 创建日志目录
mkdir -p "$SCRIPT_DIR/logs"

# 启动TCP服务器
echo "[1/3] 启动TCP服务器 (端口 8778)..."
nohup php "$SCRIPT_DIR/simple_server.php" > "$SCRIPT_DIR/logs/tcp_server.log" 2>&1 &
TCP_PID=$!
echo "✓ TCP服务器已启动 (PID: $TCP_PID)"
sleep 2

# 启动心跳处理器
echo "[2/3] 启动心跳处理器..."
nohup php "$SCRIPT_DIR/heartbeat_processor.php" > "$SCRIPT_DIR/logs/heartbeat_processor.log" 2>&1 &
HEARTBEAT_PID=$!
echo "✓ 心跳处理器已启动 (PID: $HEARTBEAT_PID)"
sleep 2

# 启动WebSocket服务器
echo "[3/3] 启动WebSocket服务器 (端口 8779)..."
nohup php "$SCRIPT_DIR/websocket_server.php" > "$SCRIPT_DIR/logs/websocket_server.log" 2>&1 &
WS_PID=$!
echo "✓ WebSocket服务器已启动 (PID: $WS_PID)"

echo ""
echo "========================================"
echo "所有服务已启动！"
echo "========================================"
echo ""
echo "TCP服务器: tcp://0.0.0.0:8778 (PID: $TCP_PID)"
echo "WebSocket服务器: ws://0.0.0.0:8779 (PID: $WS_PID)"
echo "心跳处理器: 后台处理Redis队列 (PID: $HEARTBEAT_PID)"
echo ""
echo "日志文件位置:"
echo "  - TCP服务器: $SCRIPT_DIR/logs/tcp_server.log"
echo "  - 心跳处理器: $SCRIPT_DIR/logs/heartbeat_processor.log"
echo "  - WebSocket服务器: $SCRIPT_DIR/logs/websocket_server.log"
echo ""
echo "查看日志:"
echo "  tail -f $SCRIPT_DIR/logs/tcp_server.log"
echo "  tail -f $SCRIPT_DIR/logs/heartbeat_processor.log"
echo ""
echo "停止服务:"
echo "  kill $TCP_PID $HEARTBEAT_PID $WS_PID"
echo ""

# 保存PID到文件，方便后续停止
echo "$TCP_PID" > "$SCRIPT_DIR/.tcp_server.pid"
echo "$HEARTBEAT_PID" > "$SCRIPT_DIR/.heartbeat_processor.pid"
echo "$WS_PID" > "$SCRIPT_DIR/.websocket_server.pid"

# 等待用户中断
trap "echo ''; echo '停止所有服务...'; kill $TCP_PID $HEARTBEAT_PID $WS_PID 2>/dev/null; rm -f $SCRIPT_DIR/.*.pid; echo '所有服务已停止'; exit 0" SIGINT SIGTERM

while true; do
    sleep 1
done

